<?php

namespace App\Http\Controllers\OpenShop\FeishuMini;

use App\Enums\OpenShop\InvestmentPromotion\MainProcessEnum;
use App\Http\Controllers\BaseController;
use App\Library\Rms\RmsShopApi;
use App\Models\Cruise\CruiseOrderProcessModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopAddressModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopMainProcessModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopUserIdentityCardModel;
use App\Models\Workflow\WorkflowOrderLogModel;
use App\Models\Workflow\WorkflowOrderModel;
use App\Service\Cruise\Mission\RenewInputService;
use App\Service\Renew\RenewService;
use App\Service\Workflow\WorkflowOrderService;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class RenewController extends BaseController
{
    public function info(Request $request)
    {
        $workflowNo = $request->get('workflowNo');
        $userId     = getRmsUserId();

        list($workflowOrder, $workflowNode) = RenewService::getWorkflow($workflowNo);
        $shopId = $workflowOrder->shopId;

        $renewInputService = (new RenewInputService($workflowNode->cruiseOrderId, $userId))
            ->setWorkflowOrder($workflowOrder);

        // 先用表单数据组出来基本信息
        $info = $renewInputService->getRenewUserBaseInfo();
        $address = isset($info['addressPrefixArr']) ? implode('-', array_column($info['addressPrefixArr'], 'text')) : '';
        $name = $info['name'] ?? '';
        list($age, $sex) = OpenShopUserIdentityCardModel::getCardAgeSex($info['idCard'] ?? '');
        $shopCode = (new RmsShopApi())->getShopByIds([$shopId])['data']['shopList'][0]['shopCode'] ?? 0;
        $merchantInfo = "{$name} {$sex} {$age}岁";

        // 如果开店订单有信息 - 覆盖
        $mainProcess = OpenShopMainProcessModel::query()->where('shopId', $workflowOrder->shopId)->first();
        if ($mainProcess) {
            $address     = (string)optional(OpenShopAddressModel::getData($mainProcess->orderNo))->addressPrefix;
            $shopCode    = (string)optional($mainProcess->signOrderRel)->shopCode;
            if ($mainProcess->identityCardRel->count()) {
                $name = $mainProcess->identityCardRel->name ?: '-';
                $age  = (new Carbon($mainProcess->identityCardRel->birthday))->diffInYears();
                $sex  = $mainProcess->identityCardRel->sexText;
                $merchantInfo = "{$name} {$sex} {$age}岁";
            } else {
                $merchantInfo = '';
            }
        }

        // 当前节点
        $currentNode = (new WorkflowOrderService($workflowOrder->id))->getCurrentMainNode();

        $data = [
            "mainOrderNo" => attributeGet($mainProcess, "orderNo", ""),
            'workflow' => [
                'id'         => $workflowOrder->id,
                'workflowNo' => $workflowNo,
                'nodeText'   => $currentNode ? $currentNode->name : '已完成',
                'shopCode'   => $shopCode,
                'merchantInfo' => $merchantInfo,
                'address'    => $address,
                'createdAt'  => $workflowOrder->createdAt->toDateTimeString(),
                'status'     => $workflowOrder->status,
                'statusText' => WorkflowOrderModel::STATUS_TEXT[$workflowOrder->status] ?? '',
            ],
            'logs'     => (new WorkflowOrderLogModel)->kfLogs($workflowOrder->id),
            'projects' => $renewInputService->getInputObjectFill(),
        ];

        return $this->success($data);
    }

    public function rejectNodeLists(Request $request)
    {
        $workflowNo   = $request->get('workflowNo');
        list($workflowOrder, $_) = RenewService::getWorkflow($workflowNo);

        $rejectNodeLists = (new WorkflowOrderService($workflowOrder->id))->rejectNodeLists();

        return $this->success(['lists' => $rejectNodeLists]);
    }

    public function audit(Request $request)
    {
        $workflowNo   = $request->get('workflowNo');
        $auditStatus  = $request->get('auditStatus', WorkflowOrderLogModel::AUDIT_YES);
        $auditContent = $request->get('auditContent');
        $rejectNodeId = $request->get('rejectNodeId');
        $userId       = getRmsUserId();

        $this->validate($request, [
            'workflowNo'   => 'required|string',
            'auditStatus'  => 'required|integer|' . Rule::in([
                    WorkflowOrderLogModel::AUDIT_YES,
                    WorkflowOrderLogModel::AUDIT_NO
                ]),
            'auditContent' => 'required|string',
            'rejectNodeId' => 'required_if:auditStatus,' . CruiseOrderProcessModel::STATUS_OFF . '|integer',
        ]);

        list($workflowOrder, $workflowNode) = RenewService::getWorkflow($workflowNo);

        $auditData = [
            'auditStatus'  => $auditStatus,
            'auditContent' => $auditContent,
            'rejectNodeId' => $rejectNodeId,
        ];

        (new RenewInputService($workflowNode->cruiseOrderId, $userId))
            ->setWorkflowOrder($workflowOrder)
            ->checkAudit()
            ->audit($auditData);

        return $this->success();
    }
}
